import http from 'http';
import ali from '@alicloud/pop-core';

class Request {
    client

    constructor(accessKeyId, accessKeySecret) {
        this.client = new ali({
            accessKeyId: accessKeyId,
            accessKeySecret: accessKeySecret,
            endpoint: 'https://alidns.cn-beijing.aliyuncs.com',
            apiVersion: '2015-01-09'
        });
    }

    getLocalIp(type) {
        return new Promise(((resolve, reject) => {
            http.get(`http://${type}.ipv6-test.com/api/myip.php`, response => {
                let data = ''
                response.on('data', chunk => data += chunk)
                response.on('end', () => resolve(data));
            }).on("error", err => reject(err))
        }))
    }

    getAliDnsIp({RR, domain}) {
        return new Promise((resolve, reject) => {
            this.client.request('DescribeDomainRecords', {
                "DomainName": domain,
                "RRKeyWord": RR
            }, {method: 'POST'}).then((result) => {
                const record = result.DomainRecords.Record.find(v => RR === v.RR);
                resolve(record)
            }, (ex) => {
                reject(ex)
            })
        })
    }

    executeUpdate({record, newValue}) {
        return new Promise((resolve, reject) => {
            this.client.request('UpdateDomainRecord', {
                RecordId: record.RecordId,
                RR: record.RR,
                Type: record.Type,
                Value: newValue,
                TTL: record.TTL
            }, {method: 'POST'}).then((result) => {
                resolve(result)
            }, (ex) => {
                reject(ex)
            })
        })
    }
}

export default Request
